﻿using System;
using System.Text;
using System.Web;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;
namespace Clipping.SearchUrlConstructors
{
	public class SinaNewsUrlConstructor : ISearchUrlConstruct
	{
		private Encoding _urlEncoding = Encoding.GetEncoding("gb2312");
		public Uri ConstructUrl(SearchObject searchObj)
		{
			//Contract.Requires(searchObj != null);
			string url = string.Format("http://search.sina.com.cn/?q={0}&c=news&sort=time&{1}&{2}", HttpUtility.UrlEncode(searchObj.Keyword, this._urlEncoding), getSearchTypeQueryString(searchObj.SearchType), getSearchTimeQueryString(searchObj));
			return new Uri(url);
		}
		private string getSearchTypeQueryString(SearchType searchType)
		{
			if (searchType == SearchType.SearchInTitle)
				return "range=title";
			else
				return "range=all";
		}
		private string getSearchTimeQueryString(SearchObject searchObj)
		{
			if (searchObj is TimespanSearchObject)
			{
				TimespanSearchObject so = searchObj as TimespanSearchObject;
				return getSearchTimeQueryString(so.StartTime, so.EndTime);
			}
			else if (searchObj is PeriodSearchObject)
			{
				PeriodSearchObject so = searchObj as PeriodSearchObject;
				switch (so.SearchPeriod)
				{ 
					case  SearchPeriod.全部时间:
						return "time=&stime=&etime=";
					case SearchPeriod.最近1天:
						return "time=d&stime=&etime=";
					case SearchPeriod.最近1周:
						return "time=w&stime=&etime=";
					case  SearchPeriod.最近1月 :
						return "time=m&stime=&etime=";
					case SearchPeriod.最近2天:
						return getSearchTimeQueryString(DateTime.Now.AddDays(-2), DateTime.Now);
					case SearchPeriod.最近3天 :
						return getSearchTimeQueryString(DateTime.Now.AddDays(-3), DateTime.Now);
					case SearchPeriod.最近2月 :
						return getSearchTimeQueryString(DateTime.Now.AddMonths(-2), DateTime.Now);
					case SearchPeriod.最近3月 :
						return getSearchTimeQueryString(DateTime.Now.AddMonths(-3), DateTime.Now);
					case  SearchPeriod.最近1年 :
						return getSearchTimeQueryString(DateTime.Now.AddYears(-1), DateTime.Now);
					default :
						return "time=&stime=&etime=";
				}
			}
			else
				return null;
		}
		private string getSearchTimeQueryString(DateTime startTime, DateTime endTime)
		{
			return string.Format("time=custom&stime={0:yyyy-MM-dd}&etime={1:yyyy-MM-dd}", startTime, endTime);

		}


		public Uri ConstructAbsoluteUrl(Uri baseUri, string url)
		{
			return UriHelper.ConstructAbsoluteUrl(baseUri, url);
		}
	}
}
